#!/usr/local/bin/node

import path from "node:path";
import { fileURLToPath } from "node:url";
import fse from "fs-extra";
import { glob } from "glob";

const sourceGlobs = ["./internal/service/**/*.sql"];

const outputFilePath = "./internal/database/dbgen/queries.gen.sql";

// Get root directory
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.join(__dirname, "..");

function prefixQueriesWithFileName(content: string, fileName: string): string {
  const lines = content.split("\n");
  const modifiedLines = [];

  for (const line of lines) {
    if (line.startsWith("-- name: ")) {
      modifiedLines.push(`-- file: ${fileName}`);
    }
    modifiedLines.push(line);
  }

  return modifiedLines.join("\n");
}

try {
  // Encuentra todos los archivos solicitados
  const files = [];
  for (const sourceGlob of sourceGlobs) {
    const foundFiles = await glob(path.join(rootDir, sourceGlob));
    files.push(...foundFiles);
  }

  // Lee cada archivo y los concatena en un solo string
  let outFileContent = `-- This file is auto-generated by ${__filename}. DO NOT EDIT.\n\n`;
  for (const fileName of files) {
    let content = await fse.readFile(fileName, "utf-8");
    content = prefixQueriesWithFileName(content, fileName);
    outFileContent += `${content}\n\n`;
  }

  await fse.outputFile(path.join(rootDir, outputFilePath), outFileContent);
} catch (error) {
  console.error("Error al crear el prebuild de SQLC:", error);
}
